package org.biz.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import io.jsonwebtoken.Claims;
import org.biz.common.CommonConstant;
import org.biz.common.Result;
import org.biz.modules.entity.LoginUserVO;
import org.biz.util.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zf
 * @ClassName JwtAuthenticationTokenFilter
 * @date 2024/9/9 11:02
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            //没有token，说明该接口不需要登录，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析获取UserId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时,token非法
            //响应告诉前端，需要重新登录
            Result result = new Result();
            result.setCode(500);
            result.setMessage("token失效，请重新登录!");
            //设置缓冲区中使用的编码为UTF-8
            response.setCharacterEncoding("UTF-8");
            //设置l浏览器接受内容时所使用的编码方式
            response.setContentType("*;charset = UTF-8");
            this.objectMapper.writeValue(response.getWriter(), result);
            return;
        }
        String userId = claims.getSubject();
        //从redis中获取用户信息
        LoginUserVO loginUser = redisCache.getCacheObject(CommonConstant.KEY_LOGIN_USER + userId);
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
